package com.wangpu.oa.service.impl;

import com.wangpu.oa.Application;
import com.wangpu.oa.ao.DocumentAo;
import com.wangpu.oa.ao.QueryUserAo;
import com.wangpu.oa.ao.UserAo;
import com.wangpu.oa.dao.DaoFactory;
import com.wangpu.oa.dao.DocumentDao;
import com.wangpu.oa.dao.UserDao;
import com.wangpu.oa.dto.QueryDocResult;
import com.wangpu.oa.dto.QueryResult;
import com.wangpu.oa.entity.DocumentEntity;
import com.wangpu.oa.entity.UserEntity;
import com.wangpu.oa.exception.OAException;
import com.wangpu.oa.service.Systemservice;
import com.wangpu.oa.util.MD5;
import com.wangpu.oa.util.StringUtil;
import com.wangpu.oa.util.UUID;

import static com.wangpu.oa.validate.AssertUtil.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SystemServiceImpl implements Systemservice{
	
	@Override
	public QueryResult queryUser(QueryUserAo ao,String currentUserId) throws Exception {
		//1获取清理参数
		String key=StringUtil.blankAsNull(ao.getKey());
		
		int defaultPageSize=Application.getInt("sys.default-page-size", 10);
		int pageSize=StringUtil.parseInt(ao.getPageSize(), defaultPageSize);
		
		int pageNo=StringUtil.parseInt(ao.getPageNo(), 1);
		Integer flag=StringUtil.parseInt(ao.getFlag(), null);
		
		//2执行业务逻辑
		UserDao udao=DaoFactory.getDao(UserDao.class);
		
		List<UserEntity> rows=new ArrayList<>(pageSize);
		
		int totalRows=udao.selectByLike(key, flag, currentUserId);
		
		//3组装业务结果
		QueryResult result=new QueryResult();
		
		result.setPageNo(pageNo);
		result.setPageSize(pageSize);
		result.setRows(rows);
		result.setTotalRows(totalRows);
		
		return result;
		
	}
	
	@Override
	public UserEntity addUser(UserAo ao,String currentUserId) throws Exception {
		//1获取清理参数
		String account=$("账号", ao.getAccount());
		String name=$("名称", ao.getName());
		String remark=ao.getRemark();
		//2执行业务逻辑
		//2.1账号
//		if(account==null||(account=account.trim()).length()==0) {
//			throw new OAException("");
//		}
//		if(account.length()<6||account.length()>32) {
//			throw new OAException("");
//		}
		assertBetween("账号", account, 6, 32);
		assertMatch("账号只能是字母，数字，下划线", account, "\\w+");
		
		UserDao udao=DaoFactory.getDao(UserDao.class);
//		if(udao.existAccount(account)) {
//			throw new OAException("");
//		}
		assertFalse("账号已存在", udao.exists(account, account));
		//2.2名字
		assertBetween("名称", name, 2, 10);
		assertMatch("名称必须是中文，且不能超过10个", name, "[\\u4e00-\\u9fa5]{2,10}");
		
		//2.3存入
		UserEntity u=new UserEntity();
		u.setAccount(account);
		u.setAvatar("/avatar/no-avatar.png");
		u.setCreateTime(new Date());
		UserEntity createUser=new UserEntity();
		createUser.setId(currentUserId);
		u.setCreateUser(createUser);
		u.setFlag(UserEntity.FlAG_NORMAL);
		
		u.setId(UUID.random32());
		u.setLastLoginIP(null);
		u.setLastLoginTime(null);
		u.setLastModifyPasswordTime(null);
		u.setName(name);
		
		String defaultPassword=Application.getString("sys.default-new-user-password", "123456");
		u.setPassword(MD5.encode(defaultPassword));
		u.setPhone(null);
		u.setRemark(remark);
		u.setSecurityEmail(null);
		
		udao.insert(u);
		//3组装业务结果
		return u;
	}

	@Override
	public void deleteUser(String id,String currentUserId) throws Exception {
		id=$("id",id);
		currentUserId=$("currentUserId",currentUserId);
		
		UserDao udao=DaoFactory.getDao(UserDao.class);
		UserEntity u=udao.select("id", id);
		String createUserId=u.getCreateUser().getId();
		
		if(!createUserId.equals(currentUserId)) {
			throw new OAException("非法操作");
		}
		
		udao.delete(id);
	}

	@Override
	public UserEntity modifyUser(String id, UserAo ao,String currentUserId) throws Exception {
		id=$("id",id);
		String name=StringUtil.trim(ao.getName());
		String account=StringUtil.trim(ao.getAccount());
		String remark=StringUtil.trim(ao.getRemark());
		
		UserDao udao=DaoFactory.getDao(UserDao.class);
		UserEntity old=udao.select("id", id);
		if(old==null) {
			throw new OAException("数据不存在或已被删除");
		}
		//仅允许创建人删除
		String createUserId=old.getCreateUser().getId();
		if(!createUserId.equals(currentUserId)) {
			throw new OAException("非法操作");
		}
		
		//依次来判断需要修改的属性
		Map<String, Object> needUpdateMap=new HashMap<>(4,1);
		if(name!=null) {
			if(!name.equals(old.getName())) {
				needUpdateMap.put("name", name);
				old.setName(name);
			}
		}
		
		if(account!=null) {
			if(!account.equals(old.getAccount())) {
				needUpdateMap.put("account", account);
				old.setAccount(account);
			}
		}
		
		if(remark!=null) {
			if(!remark.equals(old.getRemark())) {
				needUpdateMap.put("remark", remark);
				old.setRemark(remark);
			}
		}
		
		if(!needUpdateMap.isEmpty()) {
			udao.update(id, needUpdateMap);
		}
		
		return old;
	}

	@Override
	public UserEntity loadUser(String id,String currentUserId) throws Exception {
		id=$("id",id);
		UserDao udao=DaoFactory.getDao(UserDao.class);
		UserEntity e=udao.select("id", id); 
		
		if(e==null) {
			throw new OAException("数据已删除或不存在该数据");
		}
		
		//仅允许创建人删除
		String createUserId=e.getCreateUser().getId();
		if(!createUserId.equals(currentUserId)) {
			throw new OAException("非法操作");
		}
		
		//查询创建人
		UserEntity createUser=e.getCreateUser();
		if(createUser!=null) {
			createUser=udao.select("currentUserId", currentUserId);
			e.setCreateUser(createUser);
		}
		
		return e;
	}

	@Override
	public QueryDocResult queryDocument(DocumentAo ao, String currentUserId) throws Exception {
		//1获取清理参数
		String key=StringUtil.blankAsNull(ao.getKey());
		
		int defaultPageSize=Application.getInt("sys.default-page-size", 10);
		int pageSize=StringUtil.parseInt(ao.getPageSize(), defaultPageSize);
		
		int pageNo=StringUtil.parseInt(ao.getPageNo(), 1);
		
		//2执行业务逻辑
		DocumentDao dDao=new DocumentDao();
		
		List<DocumentEntity> rows=new ArrayList<>(pageSize);
		
		int totalRows=dDao.selectByLike(rows, key, pageSize, pageNo, currentUserId);
		
		//3组装业务结果
		QueryDocResult result=new QueryDocResult();
		
		result.setPageNo(pageNo);
		result.setPageSize(pageSize);
		result.setRows(rows);
		result.setTotalRows(totalRows);
				
		return result;
	}

	
	
}
